//
//  Data+Extensions.swift
//  MYModule
//
//  Created by 尹琼 on 2022/10/26.
//

import UIKit

extension Data {
    
    var hexDescription: String {
        return reduce("") {$0 + String(format: "%02x ", $1)}
    }
    
    
   static func getString(_ str: String?, _ limit: Int = -1) -> [UInt8] {
        var data: [UInt8] = []
        if let strData = str?.data(using: .utf8){
            if limit > 0{
                if strData.count > limit{
                    var currentLimit = limit
                    var currentStr = String(data: strData.subdata(in: 0..<currentLimit), encoding: .utf8)
                    while currentStr == nil{
                        currentLimit -= 1
                        currentStr = String(data: strData.subdata(in: 0..<currentLimit), encoding: .utf8)
                        
                    }
                    data = [UInt8](strData.subdata(in: 0..<currentLimit))
                }else {
                    data = [UInt8](strData)
                }
                
            }else {
                data = [UInt8](strData)
            }
        }
        return data
    }
}
